import http from '@/utils/request.js';
import { formattedGMTDate } from '@/utils/util'

// components/order-list/order-list.js
Component({
  
  /**
   * 组件的属性列表
   */
  properties: {
    orders: {
      type: Array,
      value: [] 
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showRecordsDialog: false,
    currentRecords: [],
    currentPlayingIndex: -1,
    currentProgress: [],
    durations: [],
    audioContexts: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onDownloadAudio(e) {
      const url = e.currentTarget.dataset.url;
      wx.showLoading({ title: '下载中...', mask: true });
      
      wx.downloadFile({
        url: url,
        success: (res) => {
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: (savedRes) => {
              wx.hideLoading();
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              });
            }
          });
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({ 
            title: '下载失败: ' + err.errMsg,
            icon: 'none'
          });
        }
      });
    },
    toggleAudio(e) {
      //显示加载
      wx.showLoading({
        title: '加载中',
        mask: true 
      })
      const index = e.currentTarget.dataset.index;
      const audioContext = this.data.audioContexts[index] || wx.createInnerAudioContext();
      
      // 新增：停止其他所有音频
      this.data.audioContexts.forEach((ctx, i) => {
        if (ctx && i !== index) {
          ctx.pause();
          ctx.seek(0);  // 重置进度
          const progress = [...this.data.currentProgress];
          progress[i] = 0;
          this.setData({ 
            currentProgress: progress,
            currentPlayingIndex: index  // 确保只有当前音频显示播放状态
          });
        }
      });

      // Initialize audio if first interaction
      if (!this.data.audioContexts[index]) {
        audioContext.src = this.data.currentRecords[index].record_file;
        audioContext.onPlay(() => {
          wx.hideLoading();
          this.setData({ currentPlayingIndex: index });
        });
        audioContext.onPause(() => {
          wx.hideLoading();
          this.setData({ currentPlayingIndex: -1 });
        });
        audioContext.onTimeUpdate(() => {
          wx.hideLoading();
          const progress = [...this.data.currentProgress];
          const durations = [...this.data.durations];
          progress[index] = audioContext.currentTime;
          durations[index] = audioContext.duration;
          this.setData({ currentProgress: progress, durations });
        });

        audioContext.onStop(() => {
          wx.hideLoading();
          const progress = [...this.data.currentProgress];
          progress[index] = 0;
          this.setData({ 
            currentProgress: progress,
            currentPlayingIndex: -1
          });
        });
        
        const audioContexts = [...this.data.audioContexts];
        audioContexts[index] = audioContext;
        this.setData({ audioContexts });
      }
  
      // Toggle play/pause
      if (audioContext.paused) {
        this.data.audioContexts.forEach((ctx, i) => {
          if (ctx && i !== index) {
            const progress = [...this.data.currentProgress];
            progress[i] = 0;
            this.setData({ currentProgress: progress });
          }
        });
        audioContext.play();
      } else {
        audioContext.pause();
      }
    },
    onShowRecords(e) {
      const orderId = e.currentTarget.dataset.id;
      const order = this.data.orders.find(item => item.id === orderId);
      //为currentProgress初始化
      const currentProgress = new Array(order.records.length).fill(0);
      order.records.map(item => {
        const ctx = wx.createInnerAudioContext();
        ctx.src = http.baseUrl + item.record_file;
        ctx.onCanplay(() => {
          const durations = [...this.data.durations];
          const index = order.records.indexOf(item);
          durations[index] = ctx.duration;
          this.setData({ durations });
        });
        return ctx;
      });
      this.setData({
        showRecordsDialog: true,
        currentProgress,
        currentRecords: order.records.map(item=>{
          item.record_file=http.baseUrl+item.record_file
          return item
        }) || [],
      });
    },
    onSeek(e) {
      const index = e.currentTarget.dataset.index;
      const seekTime = e.detail.value;
      const audioContext = this.data.audioContexts[index];
      
      if (audioContext && audioContext.duration > 0) {
        audioContext.seek(seekTime);
        const progress = [...this.data.currentProgress];
        progress[index] = seekTime;
        this.setData({ currentProgress: progress });
      }
    },
    onCloseDialog() {
      this.data.audioContexts.forEach(ctx => ctx.stop());
      const resetProgress = new Array(this.data.currentRecords.length).fill(0);
      console.log(resetProgress)
      this.setData({
        showRecordsDialog: false,
        currentPlayingIndex: -1,
        audioContexts: [],
        currentProgress: resetProgress,
        durations: resetProgress
      });
    },
    onViewDetail(e) {
      const id = e.currentTarget.dataset.id;
      console.log(id)
      wx.navigateTo({
        url: `/pages/order/detail/detail?id=${id}`
      });
    },
    onRecordDetail(e) {
      const id = e.currentTarget.dataset.id;
      const app = getApp();
      //启动录音
      app.globalData.isRecording = true;
      app.globalData.recorderManager.start();
      wx.navigateTo({
        url: `/pages/order/detail/detail?id=${id}` 
      })
    }
  },
  // 组件生命周期（替代Page的onLoad）
  lifetimes: {
    attached() { // 对应页面的onLoad
      // 这里写原本在page onLoad中的初始化逻辑
      console.log('组件被插入页面节点树时触发')
      console.log(this.properties.orders)
    },
    detached() { // 对应页面的onUnload
      // 组件卸载逻辑
    }
  },

  // 如果还需要使用页面生命周期（比如所在页面的onShow）
  pageLifetimes: {
    show() { // 对应页面的onShow
      // 页面显示时的逻辑
    },
    hide() { // 对应页面的onHide
      // 页面隐藏时的逻辑  
    }
  }
})